var list2 = []
var submit = 2
layui.use(['table', 'admin', 'ax','laydate','element','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;
	var element = layui.element
    var form = layui.form;

	//Tab switch
element.on('tab(doTabBrief)',function(data){
	console.log(data.index)
})

    laydate.render({
      elem: '#startTime'
    });

    laydate.render({
      elem: '#endTime'
    });

    laydate.render({
        elem: '#startTime2',
        value: new Date(new Date().getFullYear(), new Date().getMonth(), 1)
    });

    laydate.render({
      elem: '#endTime2'
        ,value:new Date()
    });

    /**
     * Configure Vehicles
     */
    var OrderTransport = {
        tableId: "orderTransportTable"
    };
    /**
     * Configure Confirmation
     */
    /*var OrderTransport2 = {
        tableId: "orderTransportTable2"
    };*/
    /**
     * Freight Confirmation
     */
    var OrderTransport3 = {
        tableId: "orderTransportTable3"
    };

    /**
     * Initialize table columns
     */
    OrderTransport.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'ID'},
            {width: 200,align: 'center', toolbar: '#tableBar', title: 'Operation'},
            {field: 'customerOrder', sort: true, title: 'Customer Order No.',width:150, style:'font-weight: 600;'},
            {field: 'setMentiontime', sort: true, title: 'Shipping Date', style:'font-weight: 600;', event: 'checkbox'},
            {field: 'undertime', sort: true, title: 'Order Date', style:'font-weight: 600;', event: 'checkbox'},
            {field: 'createName', title: 'Created By', style:'font-weight: 600;', event: 'checkbox'},

            {field: 'getUnitId', hide: true, title: 'Receiving Unit ID'},
            {field: 'getUnit', sort: true, title: 'Receiving Unit', style:'background-color: #dbf1e1;font-weight: 600;',width:180},
            {field: 'getLocation', title: 'Receiving Address', style:'background-color: #dbf1e1;font-weight: 600;',width:250, totalRowText: 'Total: ', event: 'checkbox'},
            {field: 'kilometer', title: 'Kilometers'},
            {field: 'totalVolume', title: 'Volume m³', totalRow: true, event: 'checkbox',
            	templet: function(d){
            		var str = "";
            		if (parseFloat(d.totalNum) != parseFloat(d.totalNum2)){
                    	str += '<span style="color:#ffaa00;font-weight: 600;">' + d.totalVolume + '</span>'
					} else {
                    	str += '<span style="font-weight: 600;">' + d.totalVolume + '</span>'
					}
            		return str
            	}
			},
            {field: 'totalNum', title: 'Quantity', totalRow: true, event: 'checkbox',
            	templet: function(d){
            		var str = "";
            		if (parseFloat(d.totalNum) != parseFloat(d.totalNum2)){
                    	str += '<span style="color:#ffaa00;font-weight: 600;">' + d.totalNum + '</span>'
					} else {
                    	str += '<span style="font-weight: 600;">' + d.totalNum + '</span>'
					}
            		return str
            	}
			},
            {field: 'nodes', title: 'Remarks', event: 'checkbox'},
            {field: 'stockPort', title: '<span style="color: #2b85e4;"><i class="layui-icon">&#xe716;</i> Stock Port</span>', style:'color: #2b85e4;', edit:'text'},
            {field: 'lineName', sort: true, title: 'Route Name', style:'font-weight: 600;', event: 'checkbox'},
            {field: 'customerName', sort: true, title: 'Customer Name', style:'font-weight: 600;', event: 'checkbox'},
            {field: 'transportNumber', sort: true, title: 'Transport Order No.', style:'font-weight: 600;', event: 'checkbox'},
            {field: 'createTime', sort: true, title: 'Creation Time', style:'font-weight: 600;', event: 'checkbox'},
        ]];
    };

    /**
     * Initialize table columns
     */
    /*OrderTransport2.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: 'ID'},
            {field: 'carnumbger', sort: true, title: 'License Plate', style:'font-weight: 600;color:#ffaa00;'},
            {field: 'driver1', sort: true, title: 'Driver Name', style:'font-weight: 600;'},
            {field: 'cartel', title: 'Contact Info', style:'font-weight: 600;'},
            {field: 'privatecarType', title: 'Vehicle Type', style:'font-weight: 600;'},
            {field: 'privatecarSurevolume', sort: true, title: 'Allowed Volume m³', style:'font-weight: 600;'},
            {field: 'privatecarSurevolume', sort: true, title: 'Load Rate %', style:'font-weight: 600;#ffaa00;', totalRowText: 'Total: ',
            	templet: function(d){
            		return (d.tooDeployVolume/d.privatecarSurevolume*100).toFixed(1)
            	}
			},
            {field: 'tooDeployVolume', sort: true, title: 'Configured Volume m³', style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true},
            {field: 'tooDeployNum', sort: true, title: 'Configured Quantity', style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true},
            {field: 'createTime', sort: true, title: 'Dispatch Time', style:'font-weight: 600;'},
            {fixed: 'right',width: 220,align: 'center', toolbar: '#tableBar2', title: 'Operation'}
        ]];
    };*/

    /**
     * Initialize table columns
     */
    OrderTransport3.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: 'ID'},
            {width: 320,align: 'center', toolbar: '#tableBar3', title: 'Operation'},
            {align: 'center', sort: true, toolbar: '#tableBar4', title: 'Loading Photos'},
            {field: 'tstate', sort: true, title: 'Status', style:'font-weight: 600;', event: 'billstateSign',
            	templet: function(d){
            		if (d.tstate == '驳回'){
                    	return '<span style="color: #FF4500;"><i class="layui-icon">&#xe615;</i>' + d.tstate + '</span>'
					} else {
                    	return '<span>' + d.tstate + '</span>'
					}
            	}
			},
            {field: 'dispatchNumber', sort: true, title: 'Transport No.', style:'font-weight: 600;',width: 180},
            {field: 'carrierName', sort: true, title: 'Carrier', style:'font-weight: 600;'},
            {field: 'carnumbger', sort: true, title: 'License Plate', style:'font-weight: 600;color:#19be6b;'},
            {field: 'driver1', sort: true, title: 'Driver Name', style:'font-weight: 600;'},
            {field: 'cartel', title: 'Contact Info', style:'font-weight: 600;'},
            {field: 'privatecarType', title: 'Vehicle Type', style:'font-weight: 600;'},
            {field: 'privatecarSurevolume', sort: true, title: 'Allowed Volume m³', style:'font-weight: 600;'},
            {field: 'privatecarSurevolume', sort: true, title: 'Load Rate %', style:'font-weight: 600;#ffaa00;', totalRowText: 'Total: ',
            	templet: function(d){
            		return (d.tooDeployVolume/d.privatecarSurevolume*100).toFixed(1)
            	}
			},
            {field: 'tooDeployVolume', sort: true, title: 'Configured Volume m³', style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true},
            {field: 'tooDeployNum', sort: true, title: 'Configured Quantity', style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true},
            {field: 'transportMoney', sort: true, title: 'Freight Value', style:'background-color: #dbf1e1;font-weight: 600;', totalRow: true},
            {field: 'lineName', sort: true, title: 'Route', style:'font-weight: 600;'},
            {field: 'createTime', sort: true, title: 'Dispatch Time', style:'font-weight: 600;'},
            {field: 'consultMoney', sort: true, title: 'System Reference Price', style:'font-weight: 600;',templet: '#consultMoneyTpl'},
        ]];
    };

    OrderTransport.search = function () {
        var queryData = {};
        queryData['getUnit'] = $("#getUnit").val();
        queryData['condition'] = $("#condition").val();
        queryData['tstate'] = $("#tstate").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['startTime2'] = $("#startTime2").val();
        queryData['endTime2'] = $("#endTime2").val();
        table.reload(OrderTransport.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
            }
        });
    };

    /*OrderTransport2.search = function () {
        var queryData = {};
        queryData['driver1'] = $("#driver1").val();
        queryData['cartel'] = $("#cartel").val();
        table.reload(OrderTransport2.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
            }
        });
    };*/

    OrderTransport3.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition_3").val();
        queryData['operateId'] = $("#operateId3").val();
        queryData['carrierId'] = $("#carrierId3").val();
        table.reload(OrderTransport3.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
            }
        });
    };

    // Render table
    var tableResult = table.render({
        elem: '#' + OrderTransport.tableId,
        url: Feng.ctxPath + '/orderTransportDispatch/findDispatchPageBySpec',
        page: true,
        limit: 240,
        height: "full-60",
		limits:[60,120,240,360,480,600,1500,3000],
        cellMinWidth: 100,
        totalRow: true ,//Enable total row
        toolbar: '#toolbarDemo', //Enable header toolbar and bind left template
        cols: OrderTransport.initColumn()
    });

    // Render table
    /*var tableResult2 = table.render({
        elem: '#' + OrderTransport2.tableId,
        url: Feng.ctxPath + '/orderTransportDispatch/findCarListBySpecToo',
        page: false,
        limit: 1000,
        height: "full-60",
        cellMinWidth: 100,
        totalRow: true ,//Enable total row
        toolbar: '#toolbarDemo', //Enable header toolbar and bind left template
        cols: OrderTransport2.initColumn()
    });*/

    // Render table
    var tableResult3 = table.render({
        elem: '#' + OrderTransport3.tableId,
        url: Feng.ctxPath + '/orderTransportDispatch/findCarListBySpecToo?tstate=too',
        page: false,
        limit: 1000,
        height: "full-60",
        cellMinWidth: 100,
        totalRow: true ,//Enable total row
        toolbar: '#toolbarDemo', //Enable header toolbar and bind left template
        cols: OrderTransport3.initColumn()
    });

    // Search button click event
    $('#btnSearch').click(function () {
        OrderTransport.search();
    });
    // Search button click event
    /*$('#btnSearch2').click(function () {
        OrderTransport2.search();
    });*/
    // Search button click event
    $('#btnSearch3').click(function () {
        OrderTransport3.search();
    });

    // Query warehouse area
    form.on('select(operateId3)',function(){
        $("#carrierId3").empty();
        $.ajax({
            url:Feng.ctxPath + '/basicCarrier/Querylist',
            dataType:"json",   //Return format as json
            async: false,
            data:{"operateId":$("#operateId3").val()},	//Parameter value
            type:"post",   //Request method
            success:function(data){
                if(data.length>0){
                    var str = "<option value=''>Select Carrier</option>";
                    $.each(data,function(key,value){
                        str += "<option value='"+value.id+"'>"+value.carrierName+"</option>";
                    });
                    $("#carrierId3").html(str);
                }
            }
        });
        form.render('select');
    });

    // Edit cell event
    table.on('edit(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;//Get all key-value pairs in the row
		var value = obj.value;//Modified value
        var field = obj.field;
		if(field == 'stockPort'){
	        var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/editStockPort?id="+data.id+"&stockPort="+value, function (data) {
	    		if (data.success) {
	                Feng.success("Update successful!");
				} else {
	                Feng.error("Update failed！"+data.message);
				}
	        }, function (data) {
	            Feng.error("Update failed!" + data.responseJSON.message + "!");
	        });
	        ajax.start();
		}
    });

    // Add details button click event
    $('#zhuijia').click(function () {
		if(list2.length > 0){
			submit = 2
            layer.open({
                type: 2,
                title: 'Add Details',
                area: ['1050px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/toYunshuCar',
            	end: function () {
					if(submit == 1){
						list2 = []
						$("#volume").text("0")
                		table.reload(OrderTransport.tableId);
                		table.reload(OrderTransport3.tableId);
					}
            	}
            });
		} else {
			layer.alert('Please select at least one order or product');
		}
    });

    // Select vehicles button click event
    $('#xuanzecar').click(function () {
		if(list2.length > 0){
			submit = 2
            layer.open({
                type: 2,
                title: 'Select Vehicles',
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/toCar',
            	end: function () {
					if(submit == 1){
						list2 = []
						$("#volume").text("0")
                		table.reload(OrderTransport.tableId);
                		table.reload(OrderTransport3.tableId);
					}
            	}
            });
		} else {
			layer.alert('Please select at least one order or product');
		}
    });

	//选择订单
	table.on('checkbox(' + OrderTransport.tableId + ')', function(obj){
		if(obj.checked){
			if(obj.type == 'all'){
				var new_list = []
				var data = table.checkStatus(OrderTransport.tableId).data
				for (var i = 0; i < data.length; i++) {
					var obj = {}
					obj.transportNumber = data[i].transportNumber
					obj.goodId = ''
					obj.num = ''
					obj.batchnumber = ''
					obj.totalVolume = data[i].totalVolume
					new_list.push(obj)
				}
				list2 = new_list
				sumVolume()
			} else if (obj.type == 'one'){
				var new_list = []
				var data = obj.data
				for (var i = 0; i < list2.length; i++) {
					if(data.transportNumber != list2[i].transportNumber){
						new_list.push(list2[i])
					}
				}
				var obj = {}
				obj.transportNumber = data.transportNumber
				obj.goodId = ''
				obj.num = ''
				obj.batchnumber = ''
				obj.totalVolume = data.totalVolume
				new_list.push(obj)
				list2 = new_list
				sumVolume()
			}
		} else {
			if(obj.type == 'all'){
				list2 = []
				$("#volume").text("0")
			} else if (obj.type == 'one'){
				var new_list = []
				var data = obj.data
				for (var i = 0; i < list2.length; i++) {
					if(data.transportNumber != list2[i].transportNumber){
						new_list.push(list2[i])
					}
				}
				list2 = new_list
				sumVolume()
			}
		}
	 });

	function sumVolume(){
		let volume = 0
		for (var i = 0; i < list2.length; i++) {
			volume += list2[i].totalVolume*1
		}
		$("#volume").text(volume.toFixed(3))
	}

    // 单击行事件
    table.on('row(' + OrderTransport.tableId + ')', function (obj) {
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + OrderTransport.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
    });
    // 单击行事件
    /*table.on('row(' + OrderTransport2.tableId + ')', function (obj) {
		$('div[lay-id="' + OrderTransport2.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + OrderTransport2.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
    });*/

    // 工具条点击事件
    table.on('tool(' + OrderTransport.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
		if(layEvent === 'checkbox'){
		　　var flag = !obj.tr.find(':checkbox:first').prop('checked');
		　　obj.tr.find(':checkbox').prop('checked',flag);
		　　if(flag){
		　　　　	obj.tr.find('.layui-form-checkbox').addClass('layui-form-checked');
				data.checked = true
				obj.update(data)//更新编辑行

				var new_list = []
				for (var i = 0; i < list2.length; i++) {
					if(data.transportNumber != list2[i].transportNumber){
						new_list.push(list2[i])
					}
				}
				var obj = {}
				obj.transportNumber = data.transportNumber
				obj.goodId = ''
				obj.num = ''
				obj.batchnumber = ''
				obj.totalVolume = data.totalVolume
				new_list.push(obj)
				list2 = new_list
				sumVolume()
		　　} else {
		　　　　	obj.tr.find('.layui-form-checkbox').removeClass('layui-form-checked');
				data.checked = false
				obj.update(data)//更新编辑行

				var new_list = []
				for (var i = 0; i < list2.length; i++) {
					if(data.transportNumber != list2[i].transportNumber){
						new_list.push(list2[i])
					}
				}
				list2 = new_list
				sumVolume()
		　　}
		}
        if (layEvent === 'chai') {
            layer.open({
                type: 2,
                title: 'Split the tracking number：'+data.customerOrder,
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/tochai?transportNumber=' + data.transportNumber,
	            end: function () {
	                sumVolume();
	            }
            });
        }
		if (layEvent === 'gaidizhi') {
			submit = 2
            layer.open({
                type: 2,
                title: 'Change address',
                area: ['1000px', '800px'],
                content: Feng.ctxPath + '/orderTransportDispatch/toGaidizhi?id=' + data.getLocationId + "&setLocationId=" + data.setLocationId,
                end: function () {
            		if(submit == 1){
            			table.reload(OrderTransport.tableId);
					}
                }
            });
    	}
    });
    // 工具条点击事件
    /*table.on('tool(' + OrderTransport2.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'chexiao') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/removeCarBySpec?carnumbger="+data.carnumbger, function (data) {
            		if (data.success) {
	                    Feng.success("撤销成功!");
	            		table.reload(OrderTransport2.tableId);
						list2 = []
						$("#volume").text("0")
                		table.reload(OrderTransport.tableId);
					} else {
	                    Feng.error("撤销失败！"+data.message);
					}
                }, function (data) {
                    Feng.error("撤销失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("确定撤销吗?", operation);
        } else if (layEvent === 'bianji'){
			submit = 2
            layer.open({
                type: 2,
                title: '编辑：'+data.carnumbger,
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/tocheck?carnumbger=' + data.carnumbger,
	            end: function () {
					if(submit == 1){
	            		table.reload(OrderTransport2.tableId);
						list2 = []
						$("#volume").text("0")
                		table.reload(OrderTransport.tableId);
					}
	            }
            });
		} else if(layEvent === 'wancheng'){
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/startCarGoods?carnumbger="+data.carnumbger, function (data) {
            		if (data.success) {
	                    Feng.success("保存成功!");
	            		table.reload(OrderTransport2.tableId);
                		table.reload(OrderTransport3.tableId);
					} else {
	                    Feng.error("保存失败！"+data.message);
					}
                }, function (data) {
                    Feng.error("保存失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("确定完成吗?", operation);
		}
    });*/
    // 工具条点击事件
    table.on('tool(' + OrderTransport3.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'chexiaod') {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/orderTransportDispatch/removeDispatchNumberBySpec?dispatchNumber="+data.dispatchNumber, function (data) {
            		if (data.success) {
	                    Feng.success("撤销成功!");
	            		table.reload(OrderTransport3.tableId);
						list2 = []
						$("#volume").text("0")
                		table.reload(OrderTransport.tableId);
					} else {
	                    Feng.error("撤销失败！"+data.message);
					}
                }, function (data) {
                    Feng.error("撤销失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("确定撤销吗?", operation);
        } else if (layEvent === 'bianjid'){
			submit = 2
            layer.open({
                type: 2,
                title: '编辑：'+data.carnumbger,
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/tochecktooyedit?dispatchNumber=' + data.dispatchNumber,
	            end: function () {
					if(submit == 1){
	            		table.reload(OrderTransport3.tableId);
						list2 = []
						$("#volume").text("0")
                		table.reload(OrderTransport.tableId);
					}
	            }
            });
		} else if(layEvent === 'tooConsultMoneyDetailed'){
            layer.open({
                type: 2,
                title: '费用信息',
                area: ['1000px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/transportCost?dispatchNumber=' + data.dispatchNumber,
            });
		} else if(layEvent === 'zhuangzaifile'){
			submit = 2
            layer.open({
                type: 2,
                title: '上传装载照片',
                area: ['750px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/edit_zhuangzaifile?dispatchNumber=' + data.dispatchNumber,
                end: function () {
					if(submit == 1){
        				table.reload(OrderTransport3.tableId);
					}
                }
            });
		} else if(layEvent === 'editmoney'){
			submit = 2
            layer.open({
                type: 2,
                title: '配置确认',
                area: ['1200px', '700px'],
                anim: 5,
                content: Feng.ctxPath + '/orderTransportDispatch/toeditmoney?dispatchNumber=' + data.dispatchNumber,
	            end: function () {
					if(submit == 1){
            			table.reload(OrderTransport3.tableId);
					}
	            }
            });
		} else if (layEvent === 'billstateSign'&&data.tstate=='驳回') {
			var index = layer.open({
				title: '审核详情：',
			    type: 1,
			    title: false, //不显示标题栏
			    closeBtn: false,
			    shade: 0.3,
		        area: '300px;',
	        	content: "<div style='padding: 50px; word-wrap: break-word;word-break: break-all;overflow: hidden; background-color: #393D49; color: #fff;line-height: 22px;  font-weight: 300;'>审核人："+data.examineName+"<br><br>审核时间："+data.examineTimes+"<br><br>批注：<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+data.examineNodes+"</div>",
	            btn: ['确定'] ,
	            yes: function(){
	                layer.close(index);
	            }
	    	});
        } else if (layEvent === 'paymentProve') {
  	    	//构建图像数组
      		var items = [];
        	if (data.zhuangzaiFileid!='') {
        		var obj = {};
        		obj.src = '/system/previewa/' + data.zhuangzaiFileid;
        		obj.title = '预览图片';
        		items.push(obj)
    	      	//定义选项（如果需要）
    	      	var options = {
    	      	    index: 0 // 此选项表示您将从第一张图片开始
    	      	};
    	      	//初始化插件
    	      	var viewer = new PhotoViewer(items, options);
			} else {
                Feng.info("暂无照片!");
			}
        }
    });

});
